package me.bincker.formwork.web.utils

import org.apache.commons.logging.LogFactory
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.stereotype.Component
import kotlin.concurrent.thread
import kotlin.reflect.KClass

/**
 * Bean获取工具
 */
@Component
class SpringUtils : ApplicationContextAware {
    companion object{
        private val log = LogFactory.getLog(SpringUtils::class.java)

        private var applicationContext: ApplicationContext? = null

        private val lock = Object()

        fun <T> getBean(clazz: Class<T>, callback: (T)->Unit){
            thread {
                if(applicationContext == null)
                    synchronized(lock) {lock.wait()}
                callback(applicationContext!!.getBean(clazz))
            }
        }

        fun <T> getBean(clazz: Class<T>): T{
            if(applicationContext == null)
                synchronized(lock) {lock.wait()}
            return applicationContext!!.getBean(clazz)
        }

        fun <T : Any> getBean(kClass: KClass<T>): T{
            return getBean(kClass.java)
        }
    }

    override fun setApplicationContext(applicationContext: ApplicationContext) {
        SpringUtils.applicationContext = applicationContext
        synchronized(lock) {lock.notifyAll()}
    }
}